import * as fse from "fs-extra";
import * as express from "express";

import { initDB } from "../db";
import { COL_MEDIA } from "../db/config";
import { resolveFile } from "../utils/fs";
import { Message } from "../utils/message";

export async function routerDeleteByKey(res: express.Response, key: string) {
	const db = await initDB();
	const media = db.collection(COL_MEDIA);
	let virtualPath: string;
	try {
		virtualPath = (await media.findOne({ key })).virtualPath;
	} catch (err) {
		const data = {
			info: "DELETE_ERR",
			error: err,
		};
		const msg = Message.success(data);
		res.send(msg);
		return;
	}
	media
		.deleteOne({ key })
		.then(() => {
			const data = {
				info: "DELETE_SUCCESS",
			};
			const msg = Message.success(data);
			res.send(msg);

			if (typeof virtualPath === "string") {
				const truePath = resolveFile(virtualPath);
				fse.unlinkSync(truePath);
			}
		})
		.catch((err) => {
			const data = {
				info: "DELETE_ERR",
				error: err,
			};
			const msg = Message.success(data);
			res.send(msg);
		});
}
